package zmee.pmas.report;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import kd.bos.algo.*;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
import kd.bos.entity.report.AbstractReportListDataPlugin;
import kd.bos.entity.report.FilterInfo;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import zmee.util.DateUtil;

import java.util.*;

/**
 * @author yss
 * @createTime 2022-12-28 11:58
 * @description 项目报表查询
 */
public class ProBudgetQuery extends AbstractReportListDataPlugin {
    private static Log log = LogFactory.getLog(ProExecuteShowQuery.class);

    @Override
    public DataSet query(ReportQueryParam queryParam, Object o) throws Throwable {
        FilterInfo filter = queryParam.getFilter();
        DynamicObjectCollection bosorg = filter.getDynamicObjectCollection("bosorg");
        DynamicObjectCollection pro = filter.getDynamicObjectCollection("pro");
        Date year = filter.getDate("year");
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(year);
        calendar.getTimeInMillis();
        int tear = calendar.get(Calendar.YEAR);//年
        Date beginYear = DateUtil.getBeginDayOfYear(tear);//本年开始时间
        Date endYear = DateUtil.getEndDayOfYear(tear);//本年结束时间

        QFilter qFYear=new QFilter("begindate", QCP.large_equals,beginYear)
                .and(new QFilter("enddate",QCP.less_equals,endYear));
        DynamicObject[] period = BusinessDataServiceHelper.load("bd_period", "id", qFYear.toArray());
        String perids="";
        for (int i = 0; i < period.length; i++) {
            if(!"".equals(perids) && perids!=null ){
                perids=perids+",";
            }
            perids=perids+"'" +period[i].getPkValue().toString()+"'";
        }
        if(bosorg!=null && bosorg.size()>0){
            StringBuilder sql=new StringBuilder();
            sql.append("/*dialect*/SELECT \n" +
                    "pmas.fprojectid as project,pmas.forgid as org,ent.fbudgetamount as amount,ent.fprojectbudgetitemid as sname ,ent.fprojectbudgetitemid as name,\n" +
                    "sum(if (ter.fperiod in("+perids+"),gsp.fcuractualpaysplitamt,0)) as monthpay\n" +
                    "from \n" +
                    "t_pmas_budget pmas \n" +
                    "left join t_pmas_budgetentry ent on pmas.fid=ent.FID \n" +
                    "left join t_pmct_paymentregentry pay on pay.fcontproid=pmas.fprojectid \n" +
                    "left join t_pmct_paymentregister ter on ter.forgid=pmas.forgid and ter.fbillstatus='C' and pay.fid=ter.fid\n" +
                    "left join t_pmct_payregsplit gsp on pay.FENTRYID=gsp.FENTRYID and gsp.fbudgetitemid=ent.fprojectbudgetitemid\n" +
                    "where pmas.FISVALID=1");
            String ids="";
            for (int i = 0; i < bosorg.size(); i++) {
                if (!"".equals(ids) && ids != null) {
                    ids = ids + ",";
                }
                ids = ids + bosorg.get(i).getPkValue().toString();
            }
            if(pro != null && pro.size() > 0) {
                String proids = "";
                for (int i = 0; i < pro.size(); i++) {
                    if (!"".equals(proids) && proids != null) {
                        proids = proids + ",";
                    }
                    proids = proids + pro.get(i).getPkValue().toString();
                }
                sql.append(" and pmas.fprojectid in("+proids+")");
            }
            sql.append(" and pmas.forgid in("+ids+")");
            sql.append(" and pmas.FYEAR >= DATE_FORMAT('"+tear+"-1-1 00:00:00','%Y-%m-%d %H:%i:%s') and pmas.FYEAR <= DATE_FORMAT('"+tear+"-12-31 23:59:59','%Y-%m-%d %H:%i:%s')  GROUP BY ent.fprojectbudgetitemid order By pmas.fprojectid asc");
            log.info(String.format("sql:%s",sql.toString()));

            DataSet dataSet = DB.queryDataSet(this.getClass().getName(), new DBRoute("scm"), sql.toString(), null);
            // 在行末尾添加一行合计 按本年预算 和 本年支付 合计
            DataSet finish = dataSet.groupBy(null).sum("amount").sum("monthpay").finish();
            // 将其他字段添加进dataset
            finish = finish.addNullField("project", "org", "sname", "name");
            // 按照原报表dataset字段，重新排序
            finish = finish.select("project", "org","amount", "sname", "name", "monthpay");
            // 将报表dataset和合计行dataset合并
            return dataSet.union(finish);
        }
        return null;
    }
}
